<?php
// .-----------------------------------------------------------------------------------
// | WE TRY THE BEST WAY
// |-----------------------------------------------------------------------------------
// | Author: 贝贝 <hebiduhebi@163.com>
// | Copyright (c) 2013-2016 杭州博也网络科技, http://www.itboye.com. All Rights Reserved.
// |-----------------------------------------------------------------------------------


namespace app\shop\api;

use app\common\api\BaseApi;
use app\shop\model\OrdersContactinfo;
use app\shop\model\OrdersItem;
use app\shop\model\Orders;
use app\extend\Page;
use app\shop\api\OrderStatusApi;
use app\shop\api\ProductAttrApi;

class OrdersApi extends BaseApi
{

    /**
     * 查询包含订单相关的信息，订单商品，
     */
    const QUERY_ALL_INFO = "shop/OrdersApi/queryAllInfo";
    /**
     * 假删除
     */
    const PRETEND_DELETE = "shop/OrdersApi/pretendDelete";
    /**
     * 添加
     */
    const COUNT = "shop/OrdersApi/count";
    /**
     * 用户购买了多少件
     */
    const COUNT_BUY = "shop/OrdersApi/countBuy";
    const SUM = "shop/OrdersApi/sum";
    /**
     * 查询，不分页
     */
    const QUERY_NO_PAGING = "shop/OrdersApi/queryNoPaging";
    /**
     * 添加
     */
    const ADD = "shop/OrdersApi/add";
    /**
     * 保存
     */
    const SAVE = "shop/OrdersApi/save";
    /**
     * 保存根据ID主键
     */
    const SAVE_BY_ID = "shop/OrdersApi/saveByID";

    /**
     * 删除
     */
    const DELETE = "shop/OrdersApi/delete";

    /**
     * 查询
     */
    const QUERY = "shop/OrdersApi/query";
    /**
     * 查询一条数据
     */
    const GET_INFO = "shop/OrdersApi/getInfo";

    /**
     * 统计指定商品的月销量
     */
    const MONTHLY_SALES = "shop/OrdersApi/monthlySales";
    /**
     * 添加订单信息
     */
    const ADD_ORDER = "shop/OrdersApi/addOrder";
    /**
     * 更新订单状态
     */
    const SAVE_PAY_STATUS = "shop/OrdersApi/savePayStatus";

    protected function _init()
    {
        $this->model = new Orders();
    }
    //用户购买了多少件 除去某些订单
    public function countBuy($uid,$pid){
        $model = $this->model->alias('o');
        //6已退货，8取消或交易关闭，12订单退回
        //order_status !=8,12,6  '`o`.`pay_status`=1 and
        $query = $model->where('`o`.`order_status` not in (8,12,6) and `i`.`p_id`='.$pid.' and `o`.`uid`='.$uid)
        ->join('LEFT JOIN itboye_orders_item as i on `i`.`order_code`=`o`.`order_code`')->field('`i`.`id`,`i`.`count`')
        // ->buildSql();
        ->select();
        // return $query;
        $count = 0;
        foreach ($query as $v) {
            $count = $count + intval($v['count']);
        }
        return $count;
    }
    /**
     *
     * 查询
     * @author hebidu <hebiduhebi@126.com>
     * @date  15/11/13 11:07
     * @copyright by itboye.com
     * @param $type
     * @param $uid
     * @param $page
     * @param $order
     * @param $params
     * @return array
     * @internal param $map
     */
    public function queryAllInfo($type,$uid,$page,$order,$params){

        //1. 设置支付状态
        if (1 == $type) {
            //待付款
            $where = ' and pay_status = '.Orders::ORDER_TOBE_PAID;
        } elseif(0 != $type) {
            //货到付款，在线已支付
            $where = ' and pay_status = '.Orders::ORDER_PAID;
        }

        //2. 设置订单状态
        if(1 == $type){
            //1. 等于待确认
            $where .= ' and order_status = '.Orders::ORDER_TOBE_CONFIRMED;
        }elseif (2 == $type) {
            //1. 已发货
            $where .= ' and order_status = '.Orders::ORDER_SHIPPED;
        }elseif(3 == $type){
            $where .= ' and order_status = '.Orders::ORDER_CANCEL;
        }elseif(0 == $type){
            $where .= ' and  order_status != '.Orders::ORDER_CANCEL;
        }

        $uid_str = " orders.uid = ".$uid;

        $list = $this->model->alias("orders")->join("LEFT JOIN __ORDERS_ITEM__ as item on item.order_code = orders.order_code")
            ->join("LEFT JOIN __ORDERS_CONTACTINFO__ as info on info.order_code = orders.order_code")
        ->field("orders.uid,info.contactname,orders.storeid,orders.order_code,orders.id,orders.price,orders.pay_status,orders.order_status,orders.createtime,orders.from,orders.brokerage_ratio,orders.tax_amount,orders.goods_amount,orders.discount_money,orders.pay_code,orders.pay_type,item.p_id as item_p_id,item.price as item_price,item.count,item.sku_desc,item.name,item.img")
            ->where($uid_str.$where) -> page($page['curpage'] . ',' . $page['size'])->order($order) ->select();

        if (false === $list) {
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        }

        $count = $this -> model -> where(' uid = '.$uid .$where) -> count();
        // 查询满足要求的总记录数
        $Page = new Page($count, $page['size']);

        //分页跳转的时候保证查询条件
        if (false !== $params) {
            foreach ($params as $key => $val) {
                $Page -> parameter[$key] = urlencode($val);
            }
        }

        // 实例化分页类 传入总记录数和每页显示的记录数
        $show = $Page -> show();

        return $this -> apiReturnSuc(["show" => $show, "list" => $list]);

    }

    /**
     * 统计指定商品的月销量
     * @param array|商品ID数组 $p_ids 商品ID数组
     * @return array
     */
    public function monthlySales(array $p_ids)
    {
        return $this->apiReturnSuc(0);
    }


    /**
     * 事务增加订单信息
     * @param $entity = array(
     *      'uid'=>购买人ID,
     *      'order_code'=>生成的订单编号
     *      'price'=>成交价格
     *      'post_price'=>运费价格
     *      'note'=>订单备注
     *      'storeid'=>店铺ID
     *      'IDCode'=>使用的IDcode
     *      'discount_money'=>该订单优惠的金额总数
     *      'tax_amount'=>税款，根据dt_tariff_code计算
     *      'from'=>订单来源
     *
     *      //订单包含的商品
     *      'items'=>array(
     *           'p_id'=>$vo['p_id'],  //商品ID
     *           'name' => $vo['name'], //商品名称
     *           'ori_price' => $vo['ori_price'],//商品原价
     *           'price' => $vo['price'],//商品成交价
     *           'img' => $vo['icon_url'], //商品图片
     *           'count' => $vo['count'],  //成交数量
     *           'sku_id' => $vo['sku_id'], //规格
     *           'sku_desc' => $vo['sku_desc'], //规格描述
     *           'createtime' => $currentTime, //创建时间
     *           'dt_tariff_code'=>$vo['dt_tariff_code'], //行邮税号
     *           'goodsUnit'=>$vo['goodsUnit'],  //计量单位编码
     *           'dt_origin_country'=>$vo['dt_origin_country'], //国别编码
     *           'weight'=>$vo['weight'], //商品单个毛重
     *      ),
     *
     *      //订单收货信息
     *      'contactname' => 'contactname',
     *       'order_code' => 'order_code',
     *       'mobile' => ['mobile'],
     *       'country' => ['country'],
     *       'province' => ['province'],
     *       'city' => ['city'],
     *       'area' => ['area'],
     *       'wxno' => ['wxno'],
     *       'detailinfo' => ['detailinfo'],
     *       'notes'=>''
     *      'id_card'=>身份证
     *
     * )
     * @return array
     */
    public function addOrder($entity)
    {
        // orders orders_contactinfo orders_item orders_
        // trace('orderapi addorder ====');
        // trace($entity);
        $flag  = true;
        $now   = time();
        $error = "";
        //1. 增加order表记录
        $order = [
            'uid'             => $entity['uid'],
            'order_code'      => $entity['order_code'],
            'price'           => $entity['price'],
            'post_price'      => $entity['post_price'],
            'note'            => $entity['note'],
            'status'          => 1,
            'pay_status'      => 0,
            'order_status'    => 2,
            'cs_status'       => 0,
            'createtime'      => $now,
            'updatetime'      => $now,
            'status_note'     => '',
            'comment_status'  => 0,
            'from'            => $entity['from'],
            'idcode'          => $entity['idcode'],
            'discount_money'  => $entity['discount_money'],
            'storeid'         => $entity['storeid'],
            'tax_amount'      => $entity['tax_amount'],
            'goods_amount'    => $entity['goods_amount'],
            'pay_type'        => $entity['pay_type'],
            'pay_balance'     => $entity['pay_balance'],
            'red_envelop_id'  => $entity['red_envelop_id'],
            'coupon_id'       => $entity['coupon_id'],
            'log'             => $entity['log'],
            // 'brokerage_ratio' => $entity['brokerage_ratio'],
        ];
        $result = $this->model->create($order, 1);
        if(!$result) return $this->apiReturnErr($this->model->getDbError());
        $this->model->startTrans();
        $result = $this->model->add();

        // trace('===');
        // trace($result);
        // addWeixinLog($result,'add order 订单 2');

        //$orderid = '';
        if ($result) {
          //  $orderid = $result['info'];
            //2. 增加order_contactinfo记录
            $orderContactInfo = [
                'uid'         => $entity['uid'],
                'contactname' => $entity['contactname'],
                'order_code'  => $entity['order_code'],
                'mobile'      => $entity['mobile'],
                'country'     => $entity['country'],
                'province'    => $entity['province'],
                'city'        => $entity['city'],
                'area'        => $entity['area'],
                'wxno'        => $entity['wxno'],
                'detailinfo'  => $entity['detailinfo'],
                'notes'       =>'',
                'postal_code' =>$entity['postal_code'],
                'id_card'     =>$entity['id_card'],
            ];

            $model = new OrdersContactinfo();
            $result = $model->create($orderContactInfo, 1);

            if ($result) {
                $result = $model->add();
                if (false === $result) {
                    //新增失败
                    $flag = false;
                    $error = $model->getDbError();
                }

            } else {//自动验证失败
                $flag = false;
                $error = $model->getError();
            }

        } else {
            $flag = false;
            $error = $this->model->getDbError();//$result['info'];
        }

        if ($flag) {
            //上面的都没有错误
            //3. 插入到orders_item表中
            $products = $entity['items'];
            $items_arr = [];
            $currentTime = time();
            $p_count = [];
            foreach ($products as $vo) {
                $pid = $vo['p_id'];
                if(isset($p_count[$pid])) $p_count[$pid] +=intval($vo['count']);
                $p_count[$pid] = intval($vo['count']);
                // trace('OrdersApi vo === ');
                $tmp = [
                    'order_code'        => $entity['order_code'],
                    'has_sku'           => '0',
                    'p_id'              => $vo['p_id'],
                    'name'              => $vo['name'],
                    'ori_price'         => $vo['ori_price'],
                    'price'             => $vo['price'],
                    'img'               => $vo['icon_url'],
                    'count'             => $vo['count'],
                    'sku_id'            => $vo['sku_id'],
                    'sku_desc'          => $vo['sku_desc'],
                    'package_id'        => $vo['package_id'],
                    'psku_id'           => $vo['psku_id'],
                    'package_price'     => $vo['package_price'],
                    'group_id'          => $vo['group_id'],
                    'createtime'        => $currentTime,
                    // 'pay_status'        =>0,
                    'dt_goods_unit'     => $vo['dt_goods_unit'],
                    'dt_origin_country' => $vo['dt_origin_country'],
                    'weight'            => $vo['weight'],
                    'tax_rate'          => isset($vo['tax_rate']) ? $vo['tax_rate']:0,
                ];

                // if (intval($vo['has_sku']) == 1) {
                //     if (!empty($vo['sku_desc']['icon_url'])) {
                //         $tmp['img'] = $vo['sku_desc']['icon_url'];
                //     }
                // }

                array_push($items_arr, $tmp);
            }
            // trace($items_arr);
            $model  = new OrdersItem();
            $result = $model->addAll($items_arr);
            if (false === $result) {
                //新增失败
                $this->model->rollback();
                return $this->apiReturnErr($model->getDbError());
            }
            // 添加销量
            foreach ($p_count as $k=>$v) {
                $r = apiCall(ProductAttrApi::SET_INC,[['pid'=>$k],'total_sales',$v]);
                if(!$r['status']){
                    $this->model->rollback();
                    return $this->apiReturnErr($r['info']);
                }
            }

        }

        // if($flag){
        //     //自动确认订单 +orderstatus
        //     $r = apiCall(OrderStatusApi::CONFIRM_ORDER,[$entity['order_code'],0,$entity['uid']]);
        //     if(!$r['status']){
        //         $this->model->rollback();
        //         return $this->apiReturnErr($r['info']);
        //     }
        // }
        if ($flag) {
            $this->model->commit();
            return $this->apiReturnSuc( $entity['order_code']);
        } else {
            $this->model->rollback();
            return $this->apiReturnErr($error);
        }

    }


    /**
     * 设置支付状态
     * @param $map
     * @param $paystatus
     * @return array
     * @internal param 数组 $orderid
     */
    public function savePayStatus($map, $paystatus)
    {

        $result = $this->model->where($map)->lock(true)->save(['pay_status' => $paystatus]);
        if (false === $result) {
            $error = $this->model->getDbError();
            return $this->apiReturnErr($error);
        } else {
            return $this->apiReturnSuc($result);
        }
    }

}
